package com.sanqi.web.controller.work;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sanqi.common.annotation.Log;
import com.sanqi.common.core.controller.BaseController;
import com.sanqi.common.core.domain.AjaxResult;
import com.sanqi.common.core.page.TableDataInfo;
import com.sanqi.common.enums.BusinessType;
import com.sanqi.common.utils.PoiExcelUtil;
import com.sanqi.common.utils.SQMapUtil;
import com.sanqi.common.utils.poi.ExcelUtil;
import com.sanqi.work.domain.WorkUser;
import com.sanqi.work.domain.WorkUserAccount;
import com.sanqi.work.manager.IWorkUserAccountManager;
import com.sanqi.work.service.IWorkUserService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 员工Controller
 * 
 * @author duany
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/work/user")
@Slf4j
@Api(tags = "员工")
public class WorkUserController extends BaseController
{
    @Autowired
    private IWorkUserService workUserService;
    @Autowired
    private IWorkUserAccountManager workUserAccountManager;
    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 查询员工列表
     */
    @PreAuthorize("@ss.hasPermi('work:user:list')")
    @GetMapping("/list")
    @ApiOperation(value = "员工-查询员工列表", notes = "员工-查询员工列表")
    public TableDataInfo list(WorkUser workUser)
    {
        startPage();
        List<WorkUser> list = workUserService.selectWorkUserList(workUser);
        if(CollUtil.isNotEmpty(list)) {
            List<String> userIdList = list.stream().map(WorkUser::getId).collect(Collectors.toList());
            List<WorkUserAccount> accountList = workUserAccountManager.queryByUserIds(userIdList);
            Map<String, WorkUserAccount> accountMap = SQMapUtil.ListToMap(accountList, WorkUserAccount::getUserId);
            for (WorkUser user : list) {
                String userId = user.getId();
                WorkUserAccount userAccount = accountMap.get(userId);
                if(null != userAccount) {
                    user.setUserAccount(userAccount.getUserAccount());
                    user.setUserOpCode(userAccount.getUserOpCode());
                }
            }
        }
        return getDataTable(list);
    }
    
    /**
     * 导入员工账号
     */
    @PreAuthorize("@ss.hasPermi('work:user:editUseAccount')")
    @PostMapping("/impUseAccount")
    @ApiOperation(value = "员工-修改员工账号", notes = "员工-修改员工账号")
    public AjaxResult impUseAccount(MultipartFile file, HttpServletRequest request) {
        try {
            Workbook workBook = PoiExcelUtil.getWorkBook(file);
            if(null != workBook) {
                this.workUserService.editUserAccount(workBook);
            } else {
                return error("未找到文件");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return this.error(e.getMessage());
        }
        return success("成功");
    }
    
    /**
     * 修改员工账号
     */
    @PreAuthorize("@ss.hasPermi('work:user:impUseAccount')")
    @PutMapping("/editUseAccount")
    @ApiOperation(value = "员工-修改员工账号", notes = "员工-修改员工账号")
    public AjaxResult editUseAccount(@RequestBody WorkUserAccount account) {
        String userId = account.getUserId();
        boolean flag = this.workUserAccountManager
                .editUserAccount(userId, account.getUserAccount(), account.getUserOpCode());
        return flag ? success("完成") : error("失败");
    }

    /**
     * 导出员工列表
     */
    @PreAuthorize("@ss.hasPermi('work:user:export')")
    @Log(title = "员工", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "员工-导出员工列表", notes = "员工-导出员工列表")
    public void export(HttpServletResponse response, WorkUser workUser)
    {
        List<WorkUser> list = workUserService.selectWorkUserList(workUser);
        ExcelUtil<WorkUser> util = new ExcelUtil<WorkUser>(WorkUser.class);
        util.exportExcel(response, list, "员工数据");
    }
    
    /**
     * 下载员工模板
     */
    @PreAuthorize("@ss.hasPermi('work:user:export')")
    @Log(title = "员工", businessType = BusinessType.EXPORT)
    @PostMapping("/exportUserTemplet")
    @ApiOperation(value = "员工-下载员工模板", notes = "员工-下载员工模板")
    public void exportUserTemplet(HttpServletResponse response, HttpServletRequest request) {
        String fileType = request.getParameter("fileType");
        String filePath = null;
        if(StrUtil.equals("1", fileType)) {
            filePath = "classpath:/file/员工导入模板.xlsx";
        } else if (StrUtil.equals("2", fileType)) {
            filePath = "classpath:/file/员工工号模板.xlsx";
        }
        Resource resource = resourceLoader.getResource(filePath);
        InputStream inputStream = null;
        OutputStream out = null;
        
        try {
            response.setHeader("content-disposition", "attachment;fileName=" + "template.xlsx");
            response.setHeader("Content-Type","text/html; charset=utf-8");
            inputStream = resource.getInputStream();
            int count = 0;
            byte[] by = new byte[1024];
            // 通过response对象获取OutputStream流
            out = response.getOutputStream();
            while ((count = inputStream.read(by)) != -1) {
                out.write(by, 0, count);// 将缓冲区的数据输出到浏览器
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 获取员工详细信息
     */
    @PreAuthorize("@ss.hasPermi('work:user:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "员工-获取员工详细信息", notes = "员工-获取员工详细信息")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(workUserService.selectWorkUserById(id));
    }

    /**
     * 新增员工
     */
    @PreAuthorize("@ss.hasPermi('work:user:add')")
    @Log(title = "员工", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "员工-新增员工", notes = "员工-新增员工")
    public AjaxResult add(@RequestBody WorkUser workUser)
    {
        return toAjax(workUserService.insertWorkUser(workUser));
    }

    /**
     * 修改员工
     */
    @PreAuthorize("@ss.hasPermi('work:user:edit')")
    @Log(title = "员工", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "员工-修改员工", notes = "员工-修改员工")
    public AjaxResult edit(@RequestBody WorkUser workUser)
    {
        return toAjax(workUserService.updateWorkUser(workUser));
    }

    /**
     * 删除员工
     */
    @PreAuthorize("@ss.hasPermi('work:user:remove')")
    @Log(title = "员工", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    @ApiOperation(value = "员工-删除员工", notes = "员工-删除员工")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        int deleteWorkUserByIds = workUserService.deleteWorkUserByIds(ids);
        if(0 != deleteWorkUserByIds) {
            this.workUserAccountManager.removeByUserIds(CollUtil.newArrayList(ids));
        }
        
        return toAjax(deleteWorkUserByIds);
    }
    
    /**
     * 导入员工信息
     * @param file
     * @return
     */
    @PostMapping("/impUserExcel")
    @Log(title = "导入员工", businessType = BusinessType.IMPORT)
    @ApiOperation(value = "员工-导入员工信息", notes = "员工-导入员工信息")
    public AjaxResult impUserExcel(MultipartFile file, HttpServletRequest request) {
        Workbook workBook = PoiExcelUtil.getWorkBook(file);
        if(null != workBook) {
            String workplaceId = request.getParameter("workplaceId");
            try {
                this.workUserService.impUserExcel(workplaceId, workBook);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return AjaxResult.error("失败");
            }
            
            return AjaxResult.success("成功");
        } else {
            return AjaxResult.error("未获取文件");
        }
    }
}
